import api_text2img from '~/data/workflow_api_text2img.json'
import api_flux from '~/data/workflow_api_flux.json'


export default function useComfyUI() {
    // const httpUrl = 'http://127.0.0.1:8188'
    const httpUrl = 'https://test.comfy.51easyai.com/'    //修改为你的ComfyUI地址
    const wsUrl = 'wss://test.comfy.51easyai.com/ws'   //修改为你的ComfyUI地址

    const positive = ref('Trump and Musk kissed on Mars, surrounded by many zombies, and there was a rocket behind them, which was marked with "spaceX"')

    const prompt_id = ref('')

    const images = ref<string[]>([])
    const images2 = ref<string[]>([])
    const clienId = 'test001'


    /**
     * 将页面的提示词参数绑定给API json
     */
    const bindPrompt = (parsm: { positive: string }) => {
        // 本地电脑无法运行Flux，可以使用最简单的文生图
        // api_text2img["6"].inputs.text = positive.value
        // //获取一个10位数的随机整数
        // api_text2img["3"].inputs.seed = Math.floor(Math.random() * 9000000000) + 1000000000
        //     使用flux
        api_flux["6"].inputs.text = positive.value
        api_flux["25"].inputs.noise_seed=Math.floor(Math.random() * 9000000000) + 1000000000
    }
    /**
     * 发送提示词
     */
    const sendPrompt = async () => {
        bindPrompt({positive: positive.value})
        const data = {
            client_id: clienId,
            prompt: api_flux, //API json
        }
        const {prompt_id: _id} = await $fetch(`/prompt`, {
            method: 'post',
            baseURL: httpUrl,
            body: data,
            mode: 'cors',
            headers: {
                'Content-Type': 'application/json',
            }
        }) as any
        if (prompt_id) {
            prompt_id.value = _id
        }
    }
    /**
     * 获取任务进度消息
     */

    /**
     * 获取结果
     */
    const getResult = async () => {
        const data = await $fetch(`/history/${prompt_id.value}`, {
            method: 'get',
            baseURL: httpUrl,
            mode: 'cors',
            headers: {
                'Content-Type': 'application/json',
            }
        }) as any
        console.log(data)
        const {outputs} = data[prompt_id.value]
        if (outputs) {
            const result = outputs['9']['images'].map(item => previewImage(item)) as string[]     //工作流不一样，这里获取的结果的节点也不一样
            console.log(result)
            images.value = [...result, ...images.value]
        }

    }
    /**
     * 预览图片
     */
    const previewImage = (outPut: {
        filename: string,
        subfolder: string,
        type: 'output' | 'input'
    }) => {
        if (outPut.subfolder) {
            return `${httpUrl}/view?filename=${outPut.filename}&subfolder=${outPut.subfolder}&type=${outPut.type}`
        } else {
            return `${httpUrl}/view?filename=${outPut.filename}&type=${outPut.type}`
        }
    }


    // const apiUrl = `http://127.0.0.1:3001`
    const apiUrl = `https://api.gptpro.com`    //修改为你部署好的后台服务器地址

    // const socketUrl='http://127.0.0.1:3002'
    const socketUrl = 'https://www.gptpro.com'   //修改为你部署好的后台服务器地址
    const socketId = ref('')
    /**
     * 封装API，调用自定义工作流
     */
    const callWorkflow = async () => {
        const data = {
            client_id: '663e19cd4fa9d8078385c7c9',//使用API登录后，获取到的user_id,修改你的服务器内存在的用户id
            socket_id: socketId.value,
            params: {
                positive: positive.value,
                seed: Math.floor(Math.random() * 9000000000) + 1000000000
            },
            options: {
                workflow_name: "flux",
            }
        }
        const res = await $fetch(`/draw/customeWorkflow`, {
            method: 'post',
            baseURL: apiUrl,
            body: data,
            mode: 'cors',
            headers: {
                'Content-Type': 'application/json',
            }
        }) as any
        if (res.status === 'success') {
            images2.value = [...res.output, ...images2.value]
        }
        console.log(res)
    }

    const token = 'sk-SFgtBiM9RZie6gRQBerIP7DCiLhbtBD0jsM3H6uM4EFPcwXM'
    /**
     * OpenAI Dalle 接口形式调用
     */
    const callDalle = async () => {
        const data = {
            prompt: positive.value,
            model: "flux",
            n: 1
        }
        const res = await $fetch(`/v1/images/generations`, {
            method: 'post',
            baseURL: apiUrl,
            body: data,
            mode: 'cors',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            }
        }) as any
        if (res) {
            images2.value = [...res.data.map(item => item.url),
                ...images2.value]

        }

    }


    return {
        positive,
        prompt_id,
        images,
        images2,
        httpUrl,
        wsUrl,
        clienId,
        socketId,
        socketUrl,

        sendPrompt,
        getResult,
        callWorkflow,
        callDalle
    }
}